﻿using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace Star.Tools.Excel
{
    public static class ExcelDownload
    {


        /// <summary>
        /// 导出Excel操作
        /// </summary>
        public static void DownLoadExcel(IWorkbook workbook, string ExcelName)
        {
            string _path = TemporarySave(workbook);
            FileStream fileStream = new FileStream(_path, FileMode.Open);
            int fileContent = (int)fileStream.Length;
            byte[] byData = new byte[fileContent];
            fileStream.Read(byData, 0, fileContent);
            fileStream.Close();
            File.Delete(_path);
            DownLoadExcel(ExcelName, byData);
        }
        /// <summary>
        /// 临时保存
        /// </summary>
        /// <returns></returns>
        public static string TemporarySave(IWorkbook workbook)
        {
            string _path = AppDomain.CurrentDomain.BaseDirectory;
            _path += string.Format(@"\TemporarySave{0}.xls", DateTime.Now.ToString("hhmmss"));
            using (FileStream file = new FileStream(_path, FileMode.Create))
            {
                workbook.Write(file);
                file.Close();
            }
            return _path;
        }

      
        /// <summary>
        /// 下载
        /// </summary>
        public static void DownLoadExcel(string ExcelName, byte[] byData)
        {
            HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}.xls", HttpUtility.UrlEncode(ExcelName)));
            HttpContext.Current.Response.AddHeader("Content-Transfer-Encoding", "binary");
            HttpContext.Current.Response.ContentType = "application/octet-stream";
            HttpContext.Current.Response.ContentEncoding = Encoding.GetEncoding("gb2312");
            HttpContext.Current.Response.BinaryWrite(byData);
            HttpContext.Current.Response.Flush();
            HttpContext.Current.Response.Close();


        }
        /// <summary>
        /// 写文件流
        /// </summary>
        /// <param name="workbook">workbook</param>
        /// <param name="fileName">文件名</param>
        private static void DownloadWebExcel(IWorkbook workbook, string fileName)
        {
            if (workbook == null) { return; }
            MemoryStream ms = new MemoryStream();
            workbook.Write(ms);
            HttpContext.Current.Response.ClearContent();
            HttpContext.Current.Response.HeaderEncoding = Encoding.Default;
            HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
            HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment; filename=" + fileName));
            HttpContext.Current.Response.BinaryWrite(ms.ToArray());
            HttpContext.Current.Response.End();
            ms.Dispose();
        }

        public static void DownloadWeb(IWorkbook workbook, string fileName)
        {
            string contentType = string.Empty;
            if (workbook.GetType() == typeof(HSSFWorkbook))
            {
                contentType = "application/vnd.ms-excel";
            }
            else if ((workbook.GetType() == typeof(XSSFWorkbook)))
            {
                contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            }

            Encoding encoding;
            string browser = HttpContext.Current.Request.UserAgent.ToUpper();
            if (browser.Contains("MS") == true && browser.Contains("IE") == true)
            {
                fileName = HttpUtility.UrlEncode(fileName);
                encoding = System.Text.Encoding.Default;
            }
            else if (browser.Contains("FIREFOX") == true)
            {
                //fileName = fileName;
                encoding = System.Text.Encoding.GetEncoding("GB2312");
            }
            else
            {
                fileName = HttpUtility.UrlEncode(fileName);
                encoding = System.Text.Encoding.Default;
            }

            var response = HttpContext.Current.Response;
            response.Clear();
            response.ContentType = contentType;
            //response.Charset = "uft-8";
            response.ContentEncoding = encoding;
            response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", fileName));

            using (MemoryStream ms = new MemoryStream())
            {
                workbook.Write(ms);
                ms.WriteTo(response.OutputStream);
            }

            response.Flush();
            response.End();

        }
   
         public static void Download(this IWorkbook workbook, string fileName)
        {
            string contentType = string.Empty;

            if (workbook.GetType() == typeof (HSSFWorkbook))
            {
                //Office2003
                contentType = "application/vnd.ms-excel";
            }
            else if ((workbook.GetType() == typeof (XSSFWorkbook)))
            {
                //Office2007
                contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            }

            var request = HttpContext.Current.Request;


            if (request.UserAgent.ToLower().Contains("msie") || request.UserAgent.ToLower().Contains("trident"))//前面是IE10，后面是IE11
            {
                fileName = HttpUtility.UrlEncode(fileName, Encoding.UTF8);
            }
            else if (request.UserAgent.ToLower().Contains("firefox") )
            {
                fileName = "\"" + fileName + "\"";
            }

            var response = HttpContext.Current.Response;
            response.Clear();
            response.ContentType = contentType;
            response.Charset = "uft-8";
            response.ContentEncoding = System.Text.Encoding.UTF8;
            response.AppendHeader("Content-Disposition", string.Format("attachment;filename={0}", fileName));

            using (MemoryStream ms = new MemoryStream())
            {
                workbook.Write(ms);
                ms.WriteTo(response.OutputStream);
            }

            response.Flush();
            response.End();

        }

        public static void Save(this IWorkbook workbook, string path)
        {
            using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write))
            {
                workbook.Write(fs);
            }
        }
    }
}
